<template>
  <div class="update-name">
    <!-- 导航栏 -->
    <van-nav-bar
      title="设置昵称"
      left-text="取消"
      right-text="完成"
      @click-left="$emit('close')"
       @click-right="onConfirm"
    />
    <!-- /导航栏 -->
    <!-- 输入框 -->
    <div class="field-wrap">
      <van-field
        v-model.trim="userName"
        rows="2"
        autosize
        type="textarea"
        maxlength="20"
        placeholder="请输入昵称"
        show-word-limit
      />
    </div>
    <!-- /输入框 -->
  </div>
</template>

<script>
import { updateUserProfile } from '@/api/user'
export default {
  name: 'UpdateName',
  components: {},
  props: {
    value: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      userName: this.value
    }
  },
  computed: {},
  watch: {},
  created () {},
  mounted () {},
  methods: {
    async  onConfirm() {
      // 1 校验数据是否合法
      if (this.userName.trim() === '') return this.$toast('昵称不能为空！')
      // 增加loading状态
      this.$toast.loading({
        message: '更新中...',
        forbidClick: true,
        duration: 0
      })
      // 2 提交数据调用接口
      try {
        await updateUserProfile({
          name: this.userName
        })
        // 提示信息
        this.$toast.success('更新用户昵称成功！')
        // 更新用户昵称
        this.$emit('input', this.userName)
        // 关闭弹层
        this.$emit('close')
      } catch (error) {
        this.$toast.fail('更新用户昵称失败！')
      }
    }
  }
}
</script>

<style scoped lang="less">
.field-wrap {
  padding: 20px;
}
</style>
